package com.soloyogame.anitoys.center.web.controller.manage.accountFinance;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.soloyogame.anitoys.center.web.controller.BaseController;
import com.soloyogame.anitoys.center.web.util.LoginUserHolder;
import com.soloyogame.anitoys.center.web.util.RequestHolder;
import com.soloyogame.anitoys.core.Services;
import com.soloyogame.anitoys.db.bean.User;
import com.soloyogame.anitoys.db.commond.Account;
import com.soloyogame.anitoys.db.commond.AccountFinance;
import com.soloyogame.anitoys.db.commond.AccountRankLog;
import com.soloyogame.anitoys.db.page.PagerModel;
import com.soloyogame.anitoys.service.AccountFinanceService;
import com.soloyogame.anitoys.service.AccountService;

/**
 * 余额管理
 * @author jiangyongzhi
 * 2016-02-15
 */
@Controller
@RequestMapping("/manage/accountFinance/")
public class AccountFinanceAction extends BaseController<Account>{

	private static final Logger logger = LoggerFactory.getLogger(AccountFinanceAction.class);
    @Autowired
	private AccountService accountService;
//    @Autowired
//    PointsManageService pointsManageService;
    @Autowired
    AccountFinanceService accountFinanceService;
    
    private static final String page_toList = "/manage/accountFinance/accountFinance";
    private static final String page_toEdit = "/manage/accountFinance/financeEdit";
    private static final String page_toDetail = "/manage/accountFinance/financeDetail";
    private AccountFinanceAction(){
        super.page_toList = page_toList;
        super.page_toEdit = page_toEdit;
        super.page_toAdd = page_toAdd;
    }
    @Override
	protected void selectListAfter(PagerModel pager) {
		pager.setPagerUrl("selectList");
	}
    
	@Override
    public Services<Account> getService() {
        return accountService;
    }

	public void setAccountService(AccountService accountService) {
		this.accountService = accountService;
	}
	
	@RequestMapping("toAccountFinance")
	public String toAccountFinance(ModelMap model) throws Exception
	{
		return page_toList;
	}
	
	/**
	 * 新增积分初始化
	 */
	@RequestMapping("toFinanceAdd")
	public String toEdit(@ModelAttribute("e") Account e, ModelMap model) throws Exception
	{
		User user = LoginUserHolder.getLoginUser();
		if (user == null || StringUtils.isBlank(user.getUsername())) 
		{
			throw new NullPointerException("登陆超时！");
		}
		
		e = getService().selectOne(e);
		AccountFinance accountFinance= accountFinanceService.selAccountFinanceByUserId(e.getId());
		if(accountFinance==null){
			e.setAmount("0");
			e.setScore(0);
		}else{
			e.setAmount(String.valueOf(accountFinance.getAmount()));
			e.setScore(accountFinance.getRank());		
		}
		model.addAttribute("e",e);
		return page_toEdit;
	}
	
	/**
	 * 查看用户部分信息及积分,余额等
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("selectList")
	public String selectList(HttpServletRequest request, @ModelAttribute("e") Account e) throws Exception
	{
		int offset = 0;//分页偏移量
        if (request.getParameter("pager.offset") != null) {
            offset = Integer
                    .parseInt(request.getParameter("pager.offset"));
        }
        if (offset < 0)
            offset = 0;
        e.setOffset(offset);
          PagerModel pager = accountService.selectPageListFinance(e);
        if (pager == null) {
            pager = new PagerModel();
        }
        // 计算总页数
        pager.setPagerSize((pager.getTotal() + pager.getPageSize() - 1)
                / pager.getPageSize());
        pager.setPagerUrl("selectList");
        request.setAttribute("pager", pager);    
		return page_toList;
	}
	/**
	 * 查看积分详情
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("toFinanceDetail")
	public String toDetail(HttpServletRequest request, @ModelAttribute("e") AccountRankLog e) throws Exception
	{
		int offset = 0;//分页偏移量
		if (request.getParameter("pager.offset") != null) {
			offset = Integer
					.parseInt(request.getParameter("pager.offset"));
		}
		if (offset < 0)
			offset = 0;
		e.setOffset(offset);
		PagerModel pager = accountFinanceService.selectRankLogPageList(e);
		if (pager == null) {
			pager = new PagerModel();
		}
		// 计算总页数
		pager.setPagerSize((pager.getTotal() + pager.getPageSize() - 1)
				/ pager.getPageSize());
		
		pager.setPagerUrl("toFinanceDetail");
		request.setAttribute("pager", pager);
		request.setAttribute("userId", e.getUserId());
		return page_toDetail;
	}
	
	/**
	 * 新增积分确认
	 * @param e
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("addFinance")
	public String addPoinst(@ModelAttribute("e") Account e, ModelMap model, RedirectAttributes flushAttrs) throws Exception
	{
		User user = LoginUserHolder.getLoginUser();
		if (user == null || StringUtils.isBlank(user.getUsername())) 
		{
			throw new NullPointerException("登陆超时！");
		}
		logger.debug("----------id:"+e.getId());
		String description = e.getRankName();//增加积分原因（该字段暂使用）
		double addAmount = 0;
		if(!StringUtils.isBlank(RequestHolder.getRequest().getParameter("addAmount")))
				addAmount = Double.valueOf(RequestHolder.getRequest().getParameter("addAmount"));
		logger.debug("----------用户："+e.getAccount()+",增加addAmount:"+addAmount);
		logger.debug("余额类型：amountType："+RequestHolder.getRequest().getParameter("amountType"));
		Integer amountType = 1;
		if(!StringUtils.isBlank(RequestHolder.getRequest().getParameter("amountType")))
			amountType = Integer.valueOf(RequestHolder.getRequest().getParameter("amountType"));
		if(StringUtils.isBlank(e.getAmount()))
			e.setAmount("0");
		if(amountType == 1 && Double.valueOf(e.getAmount())-addAmount<0){
//			model.addAttribute("amountVid","修改后的余额不能小于0！");
			flushAttrs.addFlashAttribute("message", "操作失败！修改后的余额不能小于0");
			return "redirect:selectList";
		}
		e = getService().selectOne(e);
		logger.debug("----------用户："+e.getAccount()+",初始积分score:"+e.getAccount());
		AccountRankLog accLog = new AccountRankLog();
//		accLog.setDescription("【原积分："+e.getScore()+" 新增积分："+addAmount+"】");
		e.setAmount(e.getAmount() + addAmount);
		logger.debug("----------用户："+e.getAccount()+",新增后积分score:"+e.getAccount());
		try {
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("type", amountType);
			map.put("id", e.getId());
			map.put("amount", addAmount);
			int a = accountFinanceService.updateAccountAmount(map);
			String message = "操作失败！";
			if(a>0){
				//账户积分日志记录
				accLog.setId("0");
				accLog.setUserId(e.getId());
				accLog.setAmountType(amountType);
				accLog.setAmountCount(addAmount);
				accLog.setIsOrder(0);
				accLog.setDescription(description);
//				accLog.setRemark("y");
				accLog.setRemarkUserId(user.getId());
				accLog.setRemarkUserName(user.getUsername());
				accountFinanceService.insertRankLog(accLog);
				message = "操作成功！";
			}
			flushAttrs.addFlashAttribute("message", message);
			
		} catch (Exception e2) {
			logger.error(e2.getMessage(),e);
			flushAttrs.addFlashAttribute("message", "系统异常，操作失败！");
		}
		return "redirect:selectList";
	}
	
}
